package com.echo.im.client.handler.message.suport;


import com.echo.im.client.handler.message.AbstractMessageHandler;
import com.echo.im.client.helper.OnlineStatusHelper;
import com.echo.im.common.enums.IMTerminalType;
import com.echo.im.common.model.IMRecvInfo;
import com.echo.im.common.model.message.IMPrivateMessage;
import com.echo.im.common.model.mq.OfflineMsgMqInfo;
import com.echo.im.common.vo.message.PrivateMessageVO;
import com.echo.im.mq.event.producer.EventPublisher;
import com.echo.im.mq.event.model.OfflineMessageEvent;
import com.echo.im.mq.event.model.PrivatePushMessageEvent;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: echo
 * @time: 2024-08-14
 */
@Component
public class PrivateMessageHandler extends AbstractMessageHandler<IMPrivateMessage, PrivateMessageVO> {

    private final String appName;
    private final PrivatePushMessageEvent privatePushMessageEvent;
    private final OfflineMessageEvent offlineMessageEvent;
    private final EventPublisher eventPublisher;

    public PrivateMessageHandler(OnlineStatusHelper onlineStatusHelper,
                                 @Value("${spring.application.name}")
                                 String appName,
                                 PrivatePushMessageEvent privatePushMessageEvent, OfflineMessageEvent offlineMessageEvent,
                                 EventPublisher eventPublisher) {
        super(onlineStatusHelper, appName);
        this.appName = appName;
        this.privatePushMessageEvent = privatePushMessageEvent;
        this.offlineMessageEvent = offlineMessageEvent;
        this.eventPublisher = eventPublisher;
    }

    @Override
    public void handleMessage(IMPrivateMessage message) {
        // 检查 message 和 message.getRecvTerminals() 是否为空
        if (message == null || message.getRecvTerminals() == null || message.getRecvTerminals().isEmpty()) {
            throw new IllegalArgumentException("Invalid message or terminals");
        }


        Map<Integer, List<Integer>> serverIdTerminalListMap = onlineStatusHelper.getServerIdTerminalListMap(message.getFirstRecvId(), message.getRecvTerminals());



        //如果不为空则发送消息
        if(!serverIdTerminalListMap.isEmpty()){
            serverIdTerminalListMap.forEach(
                    (serverId, terminalList) -> {
                        // 组装消息
                        IMRecvInfo<PrivateMessageVO> recvInfo = this.createRecvInfo(message, terminalList);
                        // 如果对方在线，将数据推送到消息队列，等待拉取推送
                        eventPublisher.publish(privatePushMessageEvent.topic(),privatePushMessageEvent.buildEventMessage(recvInfo));
                    }
            );
        }else {
            //如果为空就证明用户不在线，那么就直接走离线逻辑
            // 组装消息
            OfflineMsgMqInfo offlineMsgMqInfo = new OfflineMsgMqInfo(message.getFirstRecvId(), message.getData().getId(),OfflineMsgMqInfo.OfflineMsgEnum.PRIVATE_OFFLINE_MESSAGE);
            eventPublisher.publish(offlineMessageEvent.topic(),offlineMessageEvent.buildEventMessage(offlineMsgMqInfo));
        }

        // 先判断此消息是否需要推给自己，然后推送给自己的其他终端，在撤回消息的时候会用到
        if (message.getSendToSelf()) {
            // 获取所有接收端的 serverId但是除去当前端
            List<Integer> recvTerminals= IMTerminalType.codes().stream().filter(terminal -> !terminal.equals(message.getSender().getTerminal())).collect(Collectors.toList());
            serverIdTerminalListMap = onlineStatusHelper.getServerIdTerminalListMap(message.getSender().getId(),recvTerminals);
            serverIdTerminalListMap.forEach((serverId, terminalList) -> {
                // 获取终端连接的serverId
                // 如果终端在线，将数据推送到消息队列，等待拉取推送
                IMRecvInfo<PrivateMessageVO> recvInfo = this.createRecvInfoForSelf(message, terminalList);
                eventPublisher.publish(privatePushMessageEvent.topic(),privatePushMessageEvent.buildEventMessage(recvInfo));
            });
        }
    }


}
